package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.util.JsonResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;


@Component("CrmAuthenticationFilter")
public class CrmAuthenticationFilter extends FormAuthenticationFilter {

    @Override//将信息以json数据格式返回
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {

        //设置编码
        response.setContentType("application/json,charset=utf-8");

        JsonResult result = new JsonResult();
        result.mark("账号或密码错误");
        ObjectMapper mapper = new ObjectMapper();
        try {
            String result_json =  mapper.writeValueAsString(result);
            response.getWriter().write(result_json);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return false;
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        //设置编码
        response.setContentType("application/json,charset=utf-8");

        JsonResult result = new JsonResult();
        ObjectMapper mapper = new ObjectMapper();
        try {
            String result_json =  mapper.writeValueAsString(result);
            response.getWriter().write(result_json);
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        return false;
    }
}
